//
//  WXLOAuthViewController.swift
//  WXLWeoBo
//
//  Created by 王晓雷 on 16/6/25.
//  Copyright © 2016年 王晓雷. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking
class WXLOAuthViewController: UIViewController {
    override func loadView() {
        view = webView
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    // MARK: - 监听事件
    @objc private func cancelClick(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func autoFillClick(){
        print("按钮点击啦")
        let jsString = "document.getElementById('userId').value='929034281',document.getElementById('passwd').value='WXL929034281**.'"
        // JS注入
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    
    // MARK: - 设置导航
    private func setupNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelClick")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFillClick")
        navigationItem.title = "OAuth登录"
    }
    // MARK: - 设置视图
    private func setupUI(){
        view.backgroundColor = UIColor.whiteColor()
        setupNav()
    }
    
    // MARK: -  懒加载控件
    private lazy var webView: UIWebView = {
        let view = UIWebView()
        view.delegate = self
        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(REDIRECT_URI)")!
        let request = NSURLRequest(URL: url)
        view.loadRequest(request)
        return view
    }()

}

extension WXLOAuthViewController: UIWebViewDelegate {
    // 开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    // 加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    // 加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        print("xxxxx")
        
    }

    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL?.absoluteString
        // 判断urlString 是否有值 而且 他的前缀是我们的回调页
        if let u = urlString where u.hasPrefix(REDIRECT_URI) {
            // 请求参数键值对
            let query = request.URL?.query
            // 可选值判断
            if let q = query {
                // 字符串截取获得code
                let code = q.substringFromIndex("code=".endIndex)
                print("终于等到你还好没放弃：\(code)")
                loadUserAccount(code)
            }
        }

//        print(request.URL?.absoluteString)
        return true
    }
}
extension WXLOAuthViewController {
    func loadUserAccount(code: String){
        
        WXLNetworktools.sharedTools.oauthLoadUserAccount(code, success: { (response) -> () in
            // 判断请求回来的res 是否有值 而且 是否可以转成一个字典
            // 如果在在判断可选值是否有值 可以转成你想要的类型 一般情况下 as?
            guard let res = response as? [String: AnyObject] else {
                print("返回的数据不是一个字典")
                return
            }
            // 字典转模型
            let userAccount =  WXLUserAccount(dict: res)
            self.loadUserInfo(userAccount)
            }) { (error) -> () in
                print(error)
        }
        
    }
    
    func loadUserInfo(userAccount: WXLUserAccount){
         WXLNetworktools.sharedTools.oauthLoadUserInfo(userAccount, success: { (response) -> () in
            // 判断是否有值而且可以转成字典
            guard let res = response as? [String: AnyObject] else {
                return
            }
            
            userAccount.avatar_large = res["avatar_large"] as? String
            userAccount.screen_name = res["screen_name"] as? String
            // 通过归档保存数据
             WXLUserAccountTools.sharedTools.saveUserAccount(userAccount)
            print(userAccount)
            let reuslt =  WXLUserAccountTools.sharedTools.userAccount
            print(reuslt)
            }) { (error) -> () in
                print("失败\(error)")
        }
    }
}

extension WXLOAuthViewController {
    func demo(){
        // 请求url
        let urlString = "https://api.weibo.com/oauth2/access_token"
        // 请求参数
        let params = [
            "client_id":APPKEY,
            "client_secret":APPSECRET,
            "grant_type":"authorization_code",
            "code":"",
            "redirect_uri":REDIRECT_URI
        ]
        
        
        
        let manager = AFHTTPSessionManager()
        
        manager.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        manager.POST(urlString, parameters: params, progress: nil, success: { (_, response) -> Void in
            
            // 判断请求回来的res 是否有值 而且 是否可以转成一个字典
            // 如果在在判断可选值是否有值 可以转成你想要的类型 一般情况下 as?
            guard let res = response as? [String: AnyObject] else {
                print("返回的数据不是一个字典")
                return
            }
            // 字典转模型
            let userAccount =  WXLUserAccount(dict: res)
            print(userAccount)
            }) { (_, error) -> Void in
                print("失败:\(error)")
                SVProgressHUD.showErrorWithStatus("请求失败")
        }
    }
}

